<?php

/**
 * @author chenshiming & gpt
 * @license MIT
 * @since 2024-06-08
 */

namespace cn\sdnode\xstack\utils;

use Exception;

class XsRandomUtils
{
    
       /**
     * 取随机记录
     *
     * @param array $rows
     * @param int $rowCount 取记录数
     * @return array
     */
    public static function randomRows($rows, $rowCount)
    {
        if (count($rows) <= $rowCount) {
            return $rows;
        }


        $list = [];
        $indexs = array_rand($rows, $rowCount);
        if ($rowCount == 1) {
            return [$rows[$indexs]];
        }
        foreach ($indexs as $index) {
            $list[] = $rows[$index];
        }
        return $list;
    }
    public static function randomRow($rows)
    {
        if (count($rows) == 0) {
            return null;
        }
        if (count($rows) == 1) {
            return array_shift($rows);
            //return $rows[0];
        }
        $list = static::randomRows($rows, 1);
        return $list[0];
    }


    public static function randomKeys($rows, $rowCount)
    {
        $sr = [];
        if (count($rows) <= $rowCount) { 
            foreach($rows as $key=>$value){
                $sr[] = $key;
            }
            return $sr;
        }

        $sr = array_rand($rows, $rowCount);
        if ($rowCount == 1) {
            return [$sr];
        }
        return $sr;
    }
    public static function randomKey($rows)
    {
        if (count($rows) == 0) {
            return null;
        }
        if (count($rows) == 1) {
            foreach($rows as $key=>$value){
                return $key;
            }
        }
      
        $index = static::randomKeys($rows, 1);
        return $index[0];
    }
}
